<?php

class Contact {
	public $id_contact; 	//id-ul contactului in tabel
	public $id_firma; 		//id-ul firmei pentru care este contactul
	public $nume; 		
	public $sex;			//0 - male; 1 - female
	public $functie;
	public $tel_fix;
	public $tel_fax;
	public $tel_mobil;
	public $email;		
	public $version;	
	public $status;	

	function __construct($id_firma, $nume, $sex, $functie = null, $tel_fix = null, $tel_fax = null, $tel_mobil = null, $email = null) {
		$this->id_contact = CT_NOT_SAVED_YET;
		$this->id_firma = $id_firma;
		$this->nume = $nume;
		$this->sex = $sex;
		$this->functie = $functie;
		$this->tel_fix = $tel_fix;
		$this->tel_fax = $tel_fax;
		$this->tel_mobil = $tel_mobil;
		$this->email = $email;
		$this->version = 0;
		$this->status = CT_CONTACT_NEW;
	}
	
	function __destruct() {
		
	}
	
	public function queryInsertContact($db) {
		
		$query = $db->prepare("INSERT INTO `contact`  ( 	`id_firma` , 		`nume` , 
															`sex` , 			`functie`,
	                        		        				`tel_fix` ,    		`tel_fax` , 
		                        	        				`tel_mobil` , 		`email`, 
		                                					`version` 
		                               				  ) 
    							VALUES  (					:id_firma,  		:nume, 
		            										:sex,   			:functie, 
	                      									:tel_fix,   		:tel_fax, 
	                      									:tel_mobil, 		:email,
		                      								:version		                      		
		                      			);");		
		
		$query->bindParam(':id_firma', 		($this->id_firma));
		$query->bindParam(':nume', 			($this->nume));
		$query->bindParam(':sex', 			($this->sex));
		$query->bindParam(':functie', 		($this->functie));
		$query->bindParam(':tel_fix', 		($this->tel_fix));
		$query->bindParam(':tel_fax', 		($this->tel_fax));
		$query->bindParam(':tel_mobil', 	($this->tel_mobil));
		$query->bindParam(':email', 		($this->email));
		$query->bindParam(':version', 		($this->version));
	
		if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
	  		$query->closeCursor();
			throw new QueryInsertContactException("Error inserting contact " . $this->nume . $errInfo);
		}
		
  		$this->id_contact = (int) $db->lastInsertId();		
  		$query->closeCursor();
		return $this->id_contact; 				//return the contact's id
	}
	
  	public static function &queryLoadContact($db, $id_contact) {
        $query = $db->prepare("SELECT *
                    			FROM contact
                    			WHERE id = :id_contact");
                    			
        $query->bindParam(':id_contact', $id_contact);
                
        if ($query->execute() === FALSE) {

            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
        	$query->closeCursor();
        	throw new QueryLoadContactException("Failed loading contact with id " . $id_contact . $errInfo);            
        }
            
        $data = $query->fetch(PDO::FETCH_ASSOC);
        
        $contact = new Contact($data['id_firma'], $data['nume'], $data['sex']
                            , $data['functie'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email']);
        $contact->id_contact = (int) $data['id'];
        $contact->version = $data['version'];
        $query->closeCursor();
        return $contact;
    }	
    
    function queryDeleteContact($db) {
      	$query = $db->prepare("DELETE FROM contact WHERE id = :id_contact");      	
      	$query->bindParam(':id_contact', $this->id_contact);
      	      	
      	if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
      		$query->closeCursor();
      		throw new QueryDeleteContactException("Faild deleting contact with id: " . $this->id_contact . $errInfo);
      	}
      		
      	$query->closeCursor();
    	return CT_RESULT_OK;      	
    }    
    
    function queryUpdateContact($db) {
		$this->version++;

		$query = $db->prepare("UPDATE `contact`  SET 	
													`id_firma` = :id_firma , 		`nume` =  :nume, 
									 			  	`sex` = :sex, 					`functie` = :functie,
	                        		 				`tel_fix` = :tel_fix,    		`tel_fax` = :tel_fax, 	                        		 	                        		
                        		 					`tel_mobil` = :tel_mobil,    	`email` = :email,
                        		 					`version` = :version	                        		 	                        		
	                            	WHERE id = :id_contact
	                					AND version < :version");
		
		$query->bindParam(':id_firma', 	($this->id_firma));
		$query->bindParam(':nume', 		($this->nume));
		$query->bindParam(':sex', 		($this->sex));
		$query->bindParam(':functie', 	($this->functie));
		$query->bindParam(':tel_fix',   ($this->tel_fix));
		$query->bindParam(':tel_fax', 	($this->tel_fax));
		$query->bindParam(':tel_mobil',	($this->tel_mobil));		
		$query->bindParam(':email',		($this->email));		
		$query->bindParam(':version',	($this->version));		
		$query->bindParam(':id_contact',($this->id_contact));		
				               
		if ($query->execute() === FALSE) {			
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
	        $query->closeCursor();	  
			throw new QueryUpdateContactException("Failed updating contact with id: " . $this->id_contact . $errInfo);
		}
		 
		if ($query->rowCount() == 0) {

	        $query->closeCursor();
			throw new QueryWrongVersionException("Failed updating contact. Reason: wrong version!");
		}
		
       //reset the status to unmodified for a possible re-edit;
	    
        $this->status = CT_CONTACT_UNMODIFIED;		  	
		$query->closeCursor();
		
        return CT_RESULT_OK;    	
    }
    
    //deletes a contact by id; does not require an object.... STATIC
    public static function deleteContactById($db, $id_contact) {
    	$query = $db->prepare("DELETE FROM contact WHERE id = :id_contact");
    	$query->bindParam(':id_contact', $id_contact);
    	    	
      	if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
      		$query->closeCursor();
      		throw new QueryDeleteContactException("Faild deleting contact with id: " . $id_contact . $errInfo);
      	}
      		      		
    	return CT_RESULT_OK;      	
    }
    
    public static function &queryLoadByFirma($db, $id_firma) {
    	
        $query = $db->prepare("SELECT *
                    			FROM contact
                    			WHERE id_firma = :id_firma");        
        $query->bindParam(':id_firma', $id_firma);
        
        if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
			$query->closeCursor();
        	throw new QueryLoadContactException("Failed loading contact by firma; firma id = " . $id_firma . $errInfo);                    
        }
        
        $contacte = array();
        while ($data = $query->fetch(PDO::FETCH_ASSOC)) {  
            $contact = new Contact($data['id_firma'], $data['nume'], $data['sex']
                            , $data['functie'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email']);
            $contact->id_contact = (int) $data['id'];
            $contact->version = $data['version'];
            $contact->status = CT_CONT_UNMODIFIED;
            $contacte[] = $contact;
        }        

        $query->closeCursor();
        return $contacte;
    }
    
    public static function deleteContactByIdFirma($db, $id_firma) {
    	$query = $db->prepare("DELETE FROM contact WHERE id_firma = :id_firma");
    	
    	$query->bindParam(':id_firma', $id_firma);
    	    	
      	if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
      		$query->closeCursor();
      		throw new QueryDeleteContactException("Failed deleting contact with id_firma: " . $id_firma . $errInfo);
      	}
      		      		
    	return CT_RESULT_OK;      	
    }
    
    public static function queryLoadByClient($db, $conditie, $id_client, $per_pag, $pagina) {    	
    	
    	$offset = $per_pag * $pagina; 	
    			    	
        $query = "SELECT SQL_CALC_FOUND_ROWS contact.nume, contact.sex, contact.functie, contact.tel_fix, contact.tel_fax,
        				contact.tel_mobil, contact.email, contact.version, contact.id
						FROM contact
						LEFT JOIN firme ON contact.id_firma = firme.id
						WHERE firme.id_client = " . $id_client . "
							AND $conditie
						LIMIT $pagina, $per_pag";

		//echo $query;						
        if (($result = $db->query($query)) === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
           	throw new QueryLoadContactException("Failed loading contact by client; contact id = " . $id_client . $errInfo);                    
		} 
		
        $query2 = "SELECT FOUND_ROWS() AS total";

        if (($result2 = $db->query($query2)) === FALSE) {			
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
           	throw new QueryLoadContactException("Failed loading contact by client; contact id = " . $id_client . $errInfo);                    
		}         
        $data2 = $result2->fetch(PDO::FETCH_ASSOC);
        $total = $data2['total'];       
                 	
        $contacte = array();

        while ($data = $result->fetch(PDO::FETCH_ASSOC)) {        	  
            $contact = new Contact($data['id'], $data['nume'], $data['sex']
                            , $data['functie'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email']);
            $contact->id_contact = (int) $data['id'];
            $contact->version = $data['version'];
            $contact->status = CT_CONT_UNMODIFIED;
            $contacte[] = $contact;
        }        
        $result = array();
//        var_dump($total);
        $result[0] = $total;
        $result[1] = $contacte;
        return $result;    	
    }
    
    public static function isInUse($db, $id_contact) {    	
        $query = $db->prepare("SELECT *
                    			FROM comanda
                    			WHERE id_contact_sol = :id_contact
                    			OR id_contact_exec = :id_contact");        
        $query->bindParam(':id_contact', $id_contact);
        
        if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
			$query->closeCursor();
        	throw new QueryLoadComandaException("Failed loading comands by contact id = " . $id_contact . $errInfo);                    
        }
        $inUse = false;
        
        while ($data = $query->fetch(PDO::FETCH_ASSOC)) {  
            $inUse = true;
            break;
        }        

        $query->closeCursor();
        return $inUse;
    }
    
    public static function getIdOfLastContactFromFirm($db, $id_firma) {
		$query = "SELECT id FROM contact
	                   WHERE id_firma = $id_firma
					   ORDER by id DESC
					   LIMIT 1;";	

		if (($result = $db->query($query)) === FALSE) {					
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];	
           	throw new QueryLoadFirmaException("Failed loading last 1 firm for client with id: " . $id_client . $errInfo);
		}
		
		$data = $result->fetch(PDO::FETCH_ASSOC);        
        return $data['id'];	    	
    }
}

?>